var express = require('express');
var router = express.Router();

var db = require("../db/db");
var mongodb = require("mongodb");

/* GET home page. */

// 添加
router.post('/add', function(req, res) {
  var obj = req.body;
  obj.sPrice = Number(obj.sPrice)
  db.insert(res, "kaoshi", obj, function (err, result, dbt) {
    if (err) {
      res.send({
        code : 500
      })
    } else {
      res.send({
        code : 200
      })
    }
    console.log(result);
    dbt.close();

  })
});

// 获取list
router.get('/getList', function(req, res) {
  var obj = req.query;
  var page = Number(obj.page);
  var size = Number(obj.size)
  var whereObj = {
    limit: size,
    skip : (page - 1) * size
  }
  db.find(res, "kaoshi", whereObj, function (err, result, dbt, count) {
    if (err) {
      res.send({
        code : 500
      })
    } else {
      res.send({
        code: 200,
        result: result,
        count : count
        
      })
    }
    console.log(result);
    dbt.close();

  })
});

// del
router.post('/del', function(req, res) {
  var obj = req.body;
  var id = mongodb.ObjectId(obj.id);
  var whereObj = {
    _id : id
  }
  db.delete(res, "kaoshi", whereObj, function (err, result, dbt) {
    if (err) {
      res.send({
        code : 500
      })
    } else {
      res.send({
        code : 200
      })
    }
    console.log(result);
    dbt.close();

  })
});

// sort
router.get('/sort', function(req, res) {
  var obj = req.query;
  obj.sPrice = Number(obj.sPrice)
  var whereObj = {
    sort : obj
  }

  db.find(res, "kaoshi", whereObj, function (err, result, dbt) {
    if (err) {
      res.send({
        code : 500
      })
    } else {
      res.send({
        code: 200,
        result: result
        
      })
    }
    console.log(result);
    dbt.close();

  })
});

// find

router.get('/find', function(req, res) {
  var obj = req.query;
  if (obj.sPrice) {
    obj.sPrice = Number(obj.sPrice)
  }
  var whereObj = {
    find : obj
  }

  db.find(res, "kaoshi", whereObj, function (err, result, dbt) {
    if (err) {
      res.send({
        code : 500
      })
    } else {
      res.send({
        code: 200,
        result: result
        
      })
    }
    console.log(result);
    dbt.close();

  })
});

// tab
router.get('/tab', function(req, res) {
  var obj = req.query;

  var whereObj = {
    find : obj
  }

  db.find(res, "kaoshi", whereObj, function (err, result, dbt) {
    if (err) {
      res.send({
        code : 500
      })
    } else {
      res.send({
        code: 200,
        result: result
        
      })
    }
    console.log(result);
    dbt.close();

  })
});

module.exports = router;
